﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace ReplaceFileVersion
{
    public partial class CheckUpdateForm : Form
    {
        public CheckUpdateForm()
        {
            InitializeComponent();
             string fileUrl =
                "http://scloud-dlsw.br.baidu.com/package/201608/bdbrowserSetup-7.6.100.3359-3501_10002896.exe";
            fileUrl = "http://www.lzlcdn.com/app/ReplaceFileVersion/ReplaceFileVersion.exe";
            DownloadNewFile(fileUrl);
        }

        protected virtual void StartNew(string newFile)
        {
            var checkUpdate = new CheckUpdate();
            var oldFile = Application.ExecutablePath;
            checkUpdate.StartNew(oldFile, newFile);
            Environment.Exit(0);
        }
        protected void DownloadNewFile(string fileUrl)
        {
            var tmpFile = Path.GetTempFileName();
            tmpFile = Application.ExecutablePath+".download"+DateTime.Now.ToString("yyyyMMddHHmmss");
            using (var client = new WebClient())
            {
                // client.DownloadFile(fileUrl, tmpFile);
                client.DownloadFileCompleted += (sender, e) =>
                {
                    StartNew(tmpFile);
                };
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
                client.DownloadFileAsync(new Uri(fileUrl), tmpFile);
            }
        }

        protected virtual void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBarDownload.Value = e.ProgressPercentage;
            lblPersent.Text = e.ProgressPercentage.ToString() + "%";
            // Displays the operation identifier, and the transfer progress.
            //Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            //    (string)e.UserState,
            //    e.BytesReceived,
            //    e.TotalBytesToReceive,
            //    e.ProgressPercentage);
        }


    }
}
